﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace WordToHtml
{
    public partial class FrmGenerate : Form
    {
        /// <summary>
        /// 存储所有工程文件的GUID
        /// </summary>
        public Dictionary<string, string> dictSolution = new Dictionary<string, string>();

        public FrmGenerate()
        {
            InitializeComponent();
        }
        public FrmGenerate(string path)
        {
            InitializeComponent();
            this.tbDict.Text = path;
            btnBrowse.Enabled = false;
        }
        public FrmGenerate(string path, bool bo)
        {
            InitializeComponent();
            this.tbDict.Text = path;
            btnBrowse.Enabled = bo;
        }

        private void FrmGenerate_Load(object sender, EventArgs e)
        {
            //string str = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"abc_0\abc_0.csproj");
            //GenerateSolution("");
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //!String.IsNullOrEmpty(tbNameSpace.Text) &&
            //if (!String.IsNullOrEmpty(tbNameSpace.Text) && !String.IsNullOrEmpty(tbEmail.Text))
            //{
            this.tbDict.Text = "";
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.tbDict.Text = this.folderBrowserDialog1.SelectedPath;
            }
            //}
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                MyInvoke(this.tbDict.Text);
                Log("All Complete!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public static string MakePassword()
        {
            string[] pwdchars = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            int pwdlen = 4;
            string tmpstr = "";
            int iRandNum;
            Random rnd = new Random();
            for (int i = 0; i < pwdlen; i++)
            {
                iRandNum = rnd.Next(pwdchars.Length);
                tmpstr += pwdchars[iRandNum];
            }
            return tmpstr;
        }

        private void MyInvoke(string path)
        {
            //获取文件夹目录
            string[] dicts = Directory.GetDirectories(path);
            //模板目录
            string tempFilePath = AppDomain.CurrentDomain.BaseDirectory + "template\\proj.rar";
            string generatePath = AppDomain.CurrentDomain.BaseDirectory + "Generate\\";
            for (int i = 0; i < dicts.Length; i++)
            {
                //string strRandomSuffix = MakePassword();
                string folderName = dicts[i].Substring(dicts[i].LastIndexOf('\\') + 1);
                string strFolderPinYin = Chinese2Spell.Convert(folderName);
                //string strNamespace = tbNameSpace.Text + "_" + i.ToString();
                string strNamespace = String.IsNullOrEmpty(tbNameSpace.Text) ? strFolderPinYin : tbNameSpace.Text + "_" + strFolderPinYin;
                //创建项目文件夹
                string toDictPath = generatePath + strNamespace;
                //公司名
                string strComm = cbComRandom.Checked ? MakePassword() : tbCom.Text;
                Exec(tempFilePath, toDictPath, dicts[i], strNamespace, strComm, tbEmail.Text);
                MoveFiles(dicts[i], toDictPath);
                Log(String.Format("[ {0} ] Complete!", dicts[i]));
            }

            Log("Project File Generate Complete!");
            if (MessageBox.Show("是否生成解决方案文件!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                GenerateSolution(generatePath);
            }
            Log("Sulution File Generate Complete!");
        }

        /// <summary>
        /// 生成解决方案文件
        /// </summary>
        /// <param name="toDictPath"></param>
        private void GenerateSolution(string toDictPath)
        {
            if (dictSolution.Count > 0)
            {
                string solutionTempFilePath = AppDomain.CurrentDomain.BaseDirectory + "template\\solution";
                string solutionToFilePath = toDictPath + "WPSolution.sln";
                //移动文件至生成目录
                File.Copy(solutionTempFilePath, solutionToFilePath);
                string strSolution = File.ReadAllText(solutionToFilePath);

                string childTempTitle = "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"{(projectName)}\", \"{(projectName)}\\{(projectName)}.csproj\", \"{{(projectGuid)}}\"\r\nEndProject\r\n";
                string childTempBody = "    {{(projectGuid)}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n    {{(projectGuid)}}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n    {{(projectGuid)}}.Debug|Any CPU.Deploy.0 = Debug|Any CPU\r\n    {{(projectGuid)}}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n    {{(projectGuid)}}.Release|Any CPU.Build.0 = Release|Any CPU\r\n    {{(projectGuid)}}.Release|Any CPU.Deploy.0 = Release|Any CPU\r\n";
                string childTitle = "";
                string childBody = "";

                foreach (KeyValuePair<string, string> item in dictSolution)
                {
                    childTitle += childTempTitle.Replace("{(projectName)}", item.Key).Replace("{(projectGuid)}", item.Value);
                    childBody += childTempBody.Replace("{(projectName)}", item.Key).Replace("{(projectGuid)}", item.Value);
                }
                strSolution = strSolution.Replace("{(solutionTitle)}", childTitle).Replace("{(solutionBody)}", childBody);
                strSolution = strSolution.Replace("{(solutionTitle)}", childTitle).Replace("{(solutionBody)}", childBody);

                File.WriteAllText(solutionToFilePath, strSolution);
            }
            /*
                
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{(projectName)}", "{(projectName)}\{(projectName)}.csproj", "{{(projectGuid)}}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
    Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {{(projectGuid)}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {{(projectGuid)}}.Debug|Any CPU.Build.0 = Debug|Any CPU
    {{(projectGuid)}}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
    {{(projectGuid)}}.Release|Any CPU.ActiveCfg = Release|Any CPU
    {{(projectGuid)}}.Release|Any CPU.Build.0 = Release|Any CPU
    {{(projectGuid)}}.Release|Any CPU.Deploy.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
    HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

            */
        }

        /// <summary>
        /// 将zip和txt移动到生成项目的文件目录
        /// </summary>
        /// <param name="filePath">zip,txt,png文件的源目录</param>
        /// <param name="nameSpace"></param>
        private void MoveFiles(string filePath, string toDictPath)
        {
            string zipFilePath = filePath + "\\html.zip";
            string txtFilePath = filePath + "\\dict.txt";

            string png62Fp = filePath + "\\pic\\62.png";
            string png99Fp = filePath + "\\pic\\99.png";
            string png173Fp = filePath + "\\pic\\173.png";
            string png200Fp = filePath + "\\pic\\200.png";
            string png300Fp = filePath + "\\pic\\300.png";
            string png480Fp = filePath + "\\pic\\480.png";

            File.Copy(zipFilePath, toDictPath + "\\zip\\html.zip");
            File.Copy(txtFilePath, toDictPath + "\\zip\\dict.txt");

            File.Copy(png62Fp, toDictPath + "\\pic\\62.png");
            File.Copy(png99Fp, toDictPath + "\\pic\\99.png");
            File.Copy(png173Fp, toDictPath + "\\pic\\173.png");
            File.Copy(png200Fp, toDictPath + "\\pic\\200.png");
            File.Copy(png300Fp, toDictPath + "\\pic\\300.png");
            //File.Copy(png480Fp, toDictPath + "\\pic\\480.png");
        }

        /// <summary>
        /// 生成项目文件
        /// </summary>
        /// <param name="tempFilePath">模板文件目录</param>
        /// <param name="toDictPath">生成工程目录</param>
        /// <param name="childPath">子工程目录</param>
        /// <param name="nameSpace">子工程命名空间</param>
        /// <param name="com"></param>
        /// <param name="email"></param>
        private void Exec(string tempFilePath, string toDictPath, string childPath, string nameSpace, string com, string email)
        {
            //标题
            string title = childPath.Substring(childPath.LastIndexOf('\\') + 1, childPath.Length - childPath.LastIndexOf('\\') - 1);
            Directory.CreateDirectory(toDictPath);
            //解压模板
            bool boRar = UnRar(tempFilePath, toDictPath);
            if (!boRar)
            {
                MessageBox.Show("UnRar Faild!");
            }
            else
            {
                //解压成功
                //初始化参数集合
                Dictionary<string, string> dictParams = InitalizeParams(nameSpace, title, com, email);
                //遍历文件，替换内容
                #region 替换内容
                List<string> listFiles = GetFileList(toDictPath);
                foreach (string file in listFiles)
                {
                    foreach (KeyValuePair<string, string> item in dictParams)
                    {
                        string strContent = File.ReadAllText(file);
                        File.WriteAllText(file, strContent.Replace(item.Key, item.Value));
                    }
                }
                //修改project文件名称（与命名空间名称相同）
                System.IO.File.Move(toDictPath + "\\proj.csproj", toDictPath + "\\" + nameSpace + ".csproj");
                #endregion
            }

        }

        /// <summary>
        /// 获取需要替换内容的文件列表
        /// </summary>
        /// <param name="toDictPath"></param>
        /// <returns></returns>
        public List<string> GetFileList(string toDictPath)
        {
            List<string> list = new List<string>();

            string stFile_AssemblyInfo = toDictPath + "\\Properties\\AssemblyInfo.cs";
            string stFile_WMAppManifest = toDictPath + "\\Properties\\WMAppManifest.xml";
            string stFile_App = toDictPath + "\\App.xaml";
            string stFile_Appxaml = toDictPath + "\\App.xaml.cs";
            string stFile_Common = toDictPath + "\\Common.cs";
            string stFile_Detail = toDictPath + "\\Detail.xaml";
            string stFile_Detailxaml = toDictPath + "\\Detail.xaml.cs";
            string stFile_Dict = toDictPath + "\\Dict.cs";
            string stFile_MainPage = toDictPath + "\\MainPage.xaml";
            string stFile_MainPagexaml = toDictPath + "\\MainPage.xaml.cs";
            string stFile_MyZip = toDictPath + "\\MyZip.cs";
            string stFile_proj = toDictPath + "\\proj.csproj";
            string stFile_TiltEffect = toDictPath + "\\TiltEffect.cs";

            list.Add(stFile_AssemblyInfo);
            list.Add(stFile_WMAppManifest);
            list.Add(stFile_App);
            list.Add(stFile_Appxaml);
            list.Add(stFile_Common);
            list.Add(stFile_Detail);
            list.Add(stFile_Detailxaml);
            list.Add(stFile_Dict);
            list.Add(stFile_MainPage);
            list.Add(stFile_MainPagexaml);
            list.Add(stFile_MyZip);
            list.Add(stFile_proj);
            list.Add(stFile_TiltEffect);

            return list;
        }

        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="com">公司</param>
        /// <param name="email">邮件</param>
        /// <returns>返回初始化后的参数集合</returns>
        public Dictionary<string, string> InitalizeParams(string nameSpace, string title, string com, string email)
        {
            Dictionary<string, string> dicts = new Dictionary<string, string>();

            string projectGuid = System.Guid.NewGuid().ToString().ToUpper();

            dicts.Add("{(namespace)}", nameSpace);
            dicts.Add("{(title)}", title);
            dicts.Add("{(company)}", com);
            dicts.Add("{(email)}", email);
            dicts.Add("{(assemblyGuid)}", System.Guid.NewGuid().ToString().ToLower());
            dicts.Add("{(ProductID)}", System.Guid.NewGuid().ToString().ToLower());
            dicts.Add("{(projectGuid)}", projectGuid);

            if (dictSolution.Keys.Contains(nameSpace))
            {
                throw new Exception("Exception: Solution File Have The Same Guid!");
            }
            dictSolution.Add(nameSpace, projectGuid);

            return dicts;
        }

        /// <summary>
        /// 生成压缩文件
        /// </summary>
        /// <param name="rarFilePath">目标文件</param>
        /// <param name="path">源文件</param>
        /// <returns></returns>
        private bool UnRar(string rarFilePath, string toDictPath)
        {
            Process winrar = new Process();
            winrar.StartInfo.FileName = "winrar.exe";
            winrar.StartInfo.CreateNoWindow = true;
            winrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            winrar.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            winrar.StartInfo.Arguments = string.Format("x \"{0}\" \"{1}\"", rarFilePath, toDictPath);
            winrar.Start();
            winrar.WaitForExit();
            if (winrar.HasExited)
            {
                int iExitCode = winrar.ExitCode;
                if (iExitCode == 0)
                {
                    //正常完成  
                    return true;
                }
                else
                {
                    //有错  
                    return false;
                }
            }
            winrar.Close();
            return false;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.textBox1.Text = "";
        }

        public void Log(string msg)
        {
            this.textBox1.Text += msg + "\r\n";
        }
    }
}
